/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.csource.manage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.CertTypeEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.TerritoryCodeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.approval.service.impl.CaseApprovalCompleteRecordServiceImpl;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.dto.CSourceDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.ICSourceDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.user.service.impl.MemberUserCommonServiceImpl;
import com.icinfo.cloud.provider.punish.config.dto.ConfigEndDayQueryDto;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.config.service.IConfigWorkRestDayInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.*;
import com.icinfo.cloud.provider.punish.csource.manage.dto.docdata.*;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceOperateTypeEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.*;
import com.icinfo.cloud.provider.punish.csource.manage.model.*;
import com.icinfo.cloud.provider.punish.csource.manage.request.CaseSourceRegisterMainInfoRequest;
import com.icinfo.cloud.provider.punish.csource.manage.service.*;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourceBasicInfoVo;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourcePageNewVo;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourceStatisticalVo;
import com.icinfo.cloud.provider.punish.dataprocessing.dto.CaseSearchDto;
import com.icinfo.cloud.provider.punish.evideinv.dto.CaseSourceEventSaveDto;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseOfflineDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.transfer.mapper.CaseTransferRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.transfer.model.CaseTransferRecord;
import com.icinfo.cloud.provider.punish.usersign.mapper.MemberUserSignMapper;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.org.model.MemberOrg;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 案源登记主表 case_source_register_main_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月12日
 */
@Service
public class CaseSourceRegisterMainInfoServiceImpl extends MyBatisServiceSupport implements ICaseSourceRegisterMainInfoService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseSourceRegisterMainInfoServiceImpl.class);

    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;

    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;

    @Resource
    private CaseSourceMaterialRecordMapper caseSourceMaterialRecordMapper;
    @Resource
    private ICaseSourceFlowRecordService caseSourceFlowRecordService;
    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;
    @Resource
    private CaseSourceCluHandoutRecordMapper caseSourceCluHandoutRecordMapper;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Resource
    private ICaseSourceDocumentRecordService caseSourceDocumentRecordService;
    @Resource
    private ICaseOfflineDocumentRecordService caseOfflineDocumentRecordService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseSourceHandlePersonRecordService caseSourceHandlePersonRecordService;
    @Resource
    private CaseSourceFlowRecordMapper caseSourceFlowRecordMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICSourceDocCommonOperateService icSourceDocCommonOperateService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ICaseSourceRegisterDetailInfoService caseSourceRegisterDetailInfoService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private MemberUserCommonServiceImpl memberUserCommonService;
    @Resource
    private CaseApprovalCompleteRecordServiceImpl caseApprovalCompleteRecordService;
    @Resource
    private IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Resource
    private CaseTransferRecordMapper caseTransferRecordMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private IConfigWorkRestDayInfoService configWorkRestDayInfoService;
    /**
     * 案源列表
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<CaseSourcePageNewVo> caseSourceList(CaseSourceRegisterMainInfoRequest request) {
        UserDTO userInfo = UserUtil.getUserInfo();
        request.setCreateUserOrgCode(userInfo.getOrgCode());
        request.setCreateUserDeptCode(userInfo.getDeptCode());
        request.setUserDeptCode(userInfo.getDeptCode());
        request.setUserDeptType(userInfo.getDeptType());
        request.setUserOrgCode(userInfo.getOrgCode());
        // 派驻机构取部门code进行查询
        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
            request.setFlag(true);
        }
        request.setHandlePersonId(userInfo.getUserId().toString());
        List<CaseSourcePageNewVo> caseSourcePageNewVos=new ArrayList<>();
        PageHelper.startPage(request.getPageNum(), request.getLength(), request.getOrderBy());
        if(Constant.STRING_1.equals(request.getCaseSourceStatus())){
            //待分派
            caseSourcePageNewVos = caseSourceRegisterMainInfoMapper.caseSourceToDispatchList(request);
        }else if(Constant.STRING_2.equals(request.getCaseSourceStatus())){
            //已分派
            caseSourcePageNewVos = caseSourceRegisterMainInfoMapper.caseSourceIssuedList(request);
        }else {
            caseSourcePageNewVos = caseSourceRegisterMainInfoMapper.caseSourceList(request);
        }
        caseSourcePageNewVos.forEach(item -> {
            //获取当事人
            /*Example partyExample=new Example(CaseSourcePartyInfo.class);
            partyExample.createCriteria().andEqualTo("caseSourceId",item.getId()).andEqualTo("status","1");
            List<CaseSourcePartyInfo> partyInfoList=caseSourcePartyInfoMapper.selectByExample(partyExample);
            item.setCaseSourcePartyInfoList(partyInfoList);*/
            //查询最新流转记录
            /*Example flowRecordExample=new Example(CaseSourceFlowRecord.class);
            flowRecordExample.createCriteria().andEqualTo("caseSourceId",item.getId());
            flowRecordExample.setOrderByClause("flow_end_time desc");
            List<CaseSourceFlowRecord> caseSourceFlowRecords =caseSourceFlowRecordMapper.selectByExample(flowRecordExample);
            item.setFlowEndTime(caseSourceFlowRecords.get(0).getFlowEndTime());
            item.setFlowStageContent(caseSourceFlowRecords.get(0).getFlowStageContent());
            item.setFlowStageName(caseSourceFlowRecords.get(0).getFlowStageName());
            item.setFlowStageType(caseSourceFlowRecords.get(0).getFlowStageType());*/
            //查询分派指派记录
            /*Example handoutRecordExample=new Example(CaseSourceCluHandoutRecord.class);
            handoutRecordExample.createCriteria().andEqualTo("caseSourceId",item.getId());
            List<CaseSourceCluHandoutRecord> caseSourceCluHandoutRecords=caseSourceCluHandoutRecordMapper.selectByExample(handoutRecordExample);
            if (item.getCaseSourceStatus().equals(CaseSourceStatusEnum.TO_DISPATCH.getIndex()) || item.getCaseSourceStatus().equals(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex())) {
                for (CaseSourceCluHandoutRecord caseSourceCluHandoutRecord : caseSourceCluHandoutRecords) {
                    if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                            }
                        } else if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userInfo.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                        }
                        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                            }
                        } else if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                            }
                        }
                    }
                }
            }*/
            Date termTime = item.getTermTime();
            String lineCode = item.getLineCode();
            if (StrUtil.isNotEmpty(lineCode) && lineCode.startsWith(TerritoryCodeEnum.RLSB.getCode()) && !ObjectUtils.isEmpty(termTime)) {
                Date startDate = BaseUtil.getTodayEndDate();
                //判断，如果案源状态是立案审批通过，或者立案审批不通过，则取审批通过时间
                //增加案件移交的不计算截止期限
                if(!Constant.CASE_SOURCE_STAGE_LASPTG.equals(item.getCaseSourceStageCode()) && !Constant.CASE_SOURCE_STAGE_BYLASPTG.equals(item.getCaseSourceStageCode())
                        && !Constant.CASE_SOURCE_STAGE_AYYS.equals(item.getCaseSourceStageCode())){
                    int timeLimit = BaseUtil.getBetweenDays(startDate, DateUtil.endOfDay(termTime));
                    if (timeLimit < Constant.INTEGER_0) {
                        item.setTimeColor("red");
                        item.setDaysRemaining("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
                    }
                    if (timeLimit <= Constant.INTEGER_1 && timeLimit > Constant.INTEGER_0) {
                        item.setTimeColor("yellow");
                        item.setDaysRemaining("剩" + timeLimit + "天");
                    }
                    if (timeLimit > Constant.INTEGER_1) {
                        item.setTimeColor("blue");
                        item.setDaysRemaining("剩" + timeLimit + "天");
                    }
                }
            }

        });
        /*if (!ObjectUtils.isEmpty(request.getCaseSourceStatus()) && CollectionUtils.isNotEmpty(caseSourcePageNewVos)) {
            caseSourcePageNewVos = caseSourcePageNewVos.stream()
                    .filter(item -> item.getCaseSourceStatus().equals(request.getCaseSourceStatus())).collect(Collectors.toList());
        }*/
        /*BasePageRequest basePageRequest = new BasePageRequest();
        BeanUtils.copyProperties(request, basePageRequest);*/
        PageResponse<CaseSourcePageNewVo> result = new PageResponse(caseSourcePageNewVos);
//        PageHelper.startPage(request.getPageNum(), request.getLength(), request.getOrderBy());
        /*List<CaseSourcePageNewVo> caseSourcePageNewVos = caseSourceRegisterMainInfoMapper.caseSourceList(request);
        // 获取当事人信息
        List<CaseSourcePartyInfo> partyInfos = caseSourcePartyInfoMapper.selectAll();
        // 获取文书信息
        List<CaseSourceDocumentRecord> documentRecords = caseSourceDocumentRecordMapper.selectAll();
        // 获取流转记录信息
        List<CaseSourceFlowRecord> flowRecords = caseSourceFlowRecordMapper.selectList();
        // 获取指派分派信息
        List<CaseSourceCluHandoutRecord> caseSourceCluHandoutRecords = caseSourceCluHandoutRecordMapper.selectAll();
        caseSourcePageNewVos.forEach(item -> {
            // 当事人信息
            List<CaseSourcePartyInfo> partyInfoList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(partyInfos)) {
                for (CaseSourcePartyInfo partyInfo : partyInfos) {
                    if (partyInfo.getCaseSourceId().equals(item.getId())) {
                        partyInfoList.add(partyInfo);
                    }
                }
                item.setCaseSourcePartyInfoList(partyInfoList);
            }
            // 文书信息
            if (CollectionUtils.isNotEmpty(documentRecords)) {
                for (CaseSourceDocumentRecord documentRecord : documentRecords) {
                    if (item.getId().equals(documentRecord.getCaseSourceId())) {
                        item.setDocumentId(documentRecord.getId());
                        item.setDocumentApprovalStatus(documentRecord.getDocumentRecordStatus());
                    }
                }
            }
            // 流转记录信息
            List<CaseSourceFlowRecord> caseSourceFlowRecords = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(flowRecords)) {
                for (CaseSourceFlowRecord flowRecord : flowRecords) {
                    if (item.getId().equals(flowRecord.getCaseSourceId())) {
                        caseSourceFlowRecords.add(flowRecord);
                    }
                }
                if (CollectionUtils.isNotEmpty(caseSourceFlowRecords)) {
                    item.setFlowEndTime(caseSourceFlowRecords.get(0).getFlowEndTime());
                    item.setFlowStageContent(caseSourceFlowRecords.get(0).getFlowStageContent());
                    item.setFlowStageName(caseSourceFlowRecords.get(0).getFlowStageName());
                    item.setFlowStageType(caseSourceFlowRecords.get(0).getFlowStageType());
                }
            }
            // 改变案源状态
            if (item.getCaseSourceStatus().equals(CaseSourceStatusEnum.TO_DISPATCH.getIndex()) || item.getCaseSourceStatus().equals(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex())) {
                for (CaseSourceCluHandoutRecord caseSourceCluHandoutRecord : caseSourceCluHandoutRecords) {
                    if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                            }
                        } else if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userInfo.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                        }
                        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                            }
                        } else if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                            if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                    userInfo.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                                item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                            }
                        }
                    }
                }
            }
            Date termTime = item.getTermTime();
            String lineCode = item.getLineCode();
            if (StrUtil.isNotEmpty(lineCode) && lineCode.startsWith(TerritoryCodeEnum.RLSB.getCode()) && !ObjectUtils.isEmpty(termTime)) {
                Date startDate = BaseUtil.getTodayEndDate();
                //判断，如果案源状态是立案审批通过，或者立案审批不通过，则取审批通过时间
                if(!Constant.CASE_SOURCE_STAGE_LASPTG.equals(item.getCaseSourceStageCode()) && !Constant.CASE_SOURCE_STAGE_BYLASPTG.equals(item.getCaseSourceStageCode())){
                    *//*FlowRecordVo vo = caseSourceFlowRecordMapper.selectFlowRecordByCaseSourceIdAndStageType(item.getId(), item.getCaseSourceStageCode());
                    if(vo != null && vo.getFlowEndTime() != null){
                        startDate = DateUtil.endOfDay(vo.getFlowEndTime());
                    }*//*
                    int timeLimit = BaseUtil.getBetweenDays(startDate, DateUtil.endOfDay(termTime));
                    if (timeLimit < Constant.INTEGER_0) {
                        item.setTimeColor("red");
                        item.setDaysRemaining("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
                    }
                    if (timeLimit <= Constant.INTEGER_1 && timeLimit > Constant.INTEGER_0) {
                        item.setTimeColor("yellow");
                        item.setDaysRemaining("剩" + timeLimit + "天");
                    }
                    if (timeLimit > Constant.INTEGER_1) {
                        item.setTimeColor("blue");
                        item.setDaysRemaining("剩" + timeLimit + "天");
                    }
                }
            }
        });

        if (!ObjectUtils.isEmpty(request.getCaseSourceStatus()) && CollectionUtils.isNotEmpty(caseSourcePageNewVos)) {
            caseSourcePageNewVos = caseSourcePageNewVos.stream()
                    .filter(item -> item.getCaseSourceStatus().equals(request.getCaseSourceStatus())).collect(Collectors.toList());
        }
        BasePageRequest basePageRequest = new BasePageRequest();
        BeanUtils.copyProperties(request, basePageRequest);
        PageResponse<CaseSourcePageNewVo> result = new PageResponse(caseSourcePageNewVos, caseSourcePageNewVos.size(), basePageRequest);*/
        return result;
    }

    /**
     * 案源统计
     *
     * @param request
     * @return
     */
    @Override
    public CaseSourceStatisticalVo caseSourceStatistical(CaseSourceRegisterMainInfoRequest request) {
        UserDTO userInfo = UserUtil.getUserInfo();
        request.setCreateUserOrgCode(userInfo.getOrgCode());
        request.setCreateUserDeptCode(userInfo.getDeptCode());
        request.setUserDeptCode(userInfo.getDeptCode());
        request.setUserDeptType(userInfo.getDeptType());
        request.setUserOrgCode(userInfo.getOrgCode());
        // 派驻机构取部门code进行查询
        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
            request.setFlag(true);
        }
        request.setHandlePersonId(userInfo.getUserId().toString());
        CaseSourceStatisticalVo statisticalVo = new CaseSourceStatisticalVo();
        statisticalVo.setTotalNumber(caseSourceRegisterMainInfoMapper.caseSourceStatistical(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
        statisticalVo.setToDispatchNumber(caseSourceRegisterMainInfoMapper.selectCountToDispatch(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
        statisticalVo.setHasBeenIssuedNumber(caseSourceRegisterMainInfoMapper.selectCountIssued(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.PRE_SURVEY.getIndex());
        statisticalVo.setPreSurveyNumber(caseSourceRegisterMainInfoMapper.caseSourceStatistical(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.REGISTERED.getIndex());
        statisticalVo.setRegisteredNumber(caseSourceRegisterMainInfoMapper.caseSourceStatistical(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.NO_REGISTERED.getIndex());
        statisticalVo.setNoRegisteredNumber(caseSourceRegisterMainInfoMapper.caseSourceStatistical(request));
        request.setCaseSourceStatus(CaseSourceStatusEnum.TRANSFER.getIndex());
        statisticalVo.setTransferNumber(caseSourceRegisterMainInfoMapper.caseSourceStatistical(request));
        return statisticalVo;
    }

    /**
     * 获取案源列表数据
     *
     * @param request
     * @return
     */
    private List<CaseSourcePageNewVo> getCaseSourcePageNewVoList(CaseSourceRegisterMainInfoRequest request) {
        UserDTO userDTO=UserUtil.getUserInfo();
        List<CaseSourcePageNewVo> caseSourcePageNewVos = caseSourceRegisterMainInfoMapper.caseSourceList(request);
        List<CaseSourceCluHandoutRecord> caseSourceCluHandoutRecords = caseSourceCluHandoutRecordMapper.selectAll();
        caseSourcePageNewVos.forEach(item -> {
            if (item.getCaseSourceStatus().equals(CaseSourceStatusEnum.TO_DISPATCH.getIndex()) || item.getCaseSourceStatus().equals(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex())) {
                for (CaseSourceCluHandoutRecord caseSourceCluHandoutRecord : caseSourceCluHandoutRecords) {
                    if (Constant.STRING_2.equals(userDTO.getDeptType())) {
                        if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userDTO.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                        }
                    } else if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                        if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userDTO.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignedOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                        }
                    }
                    if (Constant.STRING_2.equals(userDTO.getDeptType())) {
                        if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userDTO.getDeptCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                        }
                    } else if (!ObjectUtils.isEmpty(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                        if (item.getId().equals(caseSourceCluHandoutRecord.getCaseSourceId()) &&
                                userDTO.getOrgCode().equals(caseSourceCluHandoutRecord.getCluAssignUserOrgCode())) {
                            item.setCaseSourceStatus(CaseSourceStatusEnum.HAS_BEEN_ISSUED.getIndex());
                        }
                    }
                }
            }
        });
        if (!ObjectUtils.isEmpty(request.getCaseSourceStatus()) && CollectionUtils.isNotEmpty(caseSourcePageNewVos)) {
            caseSourcePageNewVos = caseSourcePageNewVos.stream()
                    .filter(item -> item.getCaseSourceStatus().equals(request.getCaseSourceStatus())).collect(Collectors.toList());
        }
        return caseSourcePageNewVos;
    }

    /**
     * 案源登记
     *
     * @param saveDto
     * @return {@link int}
     * @author liyafeng
     * @date 2022/8/12
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int saveCaseSourceRegisterMainInfo(CaseSourceRegisterMainInfoDto saveDto) {
        String id;
        UserDTO userDTO = UserUtil.getUserInfo();
        if (StringUtils.isBlank(saveDto.getId())){
            //先生成案源id
            id = StringUtils.uuid();
            //流转日志保存 案源立案
            saveCaseSourceFlowRecord(id, userDTO, saveDto);
        } else {
            id = saveDto.getId();
        }
        //案源信息保存
        saveCaseSourceMainInfo(id, userDTO, saveDto);
        //当事人信息保存
        saveCaseSourcePartyInfo(id, saveDto.getCaseSourcePartyInfoList());
        //附件保存
        saveCaseSourceMaterialRecord(id, userDTO, saveDto);
        //生成案源登记表文书
        CaseSourceAppointInfo appointInfo = new CaseSourceAppointInfo();
        if (StringUtils.isNotBlank(saveDto.getHandlePersonMainId())) {
            appointInfo.setCluAppointUserId(saveDto.getHandlePersonMainId());
            appointInfo.setCluAppointUserName(saveDto.getHandlePersonMainName());
            appointInfo.setCluAssignDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        }
        //新增案源事件-证据端
        saveCaseSourceEvent(saveDto, id);
        saveCaseSourceRegisterDoc(id, CaseSourceOperateTypeEnum.REGISTER.getCode(), appointInfo);
        return 1;
    }

    /**
     * 同步证据端案源事件
     *
     * @param saveDto
     * @param caseSourceId
     * @return
     * @author liyafeng
     * @date 2022/8/19
     */
    private void saveCaseSourceEvent(CaseSourceRegisterMainInfoDto saveDto, String caseSourceId) {
        try {
            CaseSourceEventSaveDto dto = new CaseSourceEventSaveDto();
            dto.setCaseSourceId(caseSourceId);
            dto.setCaseSourceName(saveDto.getCaseSourceName());
            dto.setTerritoryCode(saveDto.getLineCode().substring(0, 4));
            evidenceInventoryService.saveCaseSourceEvent(dto);
        } catch (Exception e) {
            logger.error("新增案源事件失败", e);
        }
    }

    /**
     * 流转日志保存 案源立案
     *
     * @param id
     * @param userDTO
     * @param saveDto
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveCaseSourceFlowRecord(String id, UserDTO userDTO, CaseSourceRegisterMainInfoDto saveDto) {
        FlowCommonDto dto = new FlowCommonDto();
        dto.setCaseSourceId(id);
        dto.setFlowStartTime(new Date());
        dto.setFlowEndTime(new Date());
        dto.setStartPersonName(userDTO.getRealName());
        dto.setStartPersonOrgName(userDTO.getOrgName());
        dto.setStartPersonDeptName(userDTO.getDeptName());
        dto.setFlowStageType(Constant.CASE_SOURCE_STAGE_AYDJ);
        caseSourceFlowRecordService.saveCommonFlowRecord(dto);
        if (StringUtils.isNotBlank(saveDto.getHandlePersonMainId())) {
            //如果已指派  生成指派流转日志
            dto.setFlowStartTime(DateUtils.addMilliseconds(new Date(), 100));
            dto.setFlowEndTime(DateUtils.addMilliseconds(new Date(), 100));
            dto.setFlowStartTime(DateUtils.addMilliseconds(new Date(), 100));
            dto.setFlowEndTime(DateUtils.addMilliseconds(new Date(), 100));
            dto.setFlowStageType(Constant.CASE_SOURCE_STAGE_AYZP);
            dto.setCommonExplain("");
            List<AppointedPersonInfo> appointedPersonInfos = new ArrayList<>();
            AppointedPersonInfo appointedMainPersonInfo = new AppointedPersonInfo();
            appointedMainPersonInfo.setPersonName(saveDto.getHandlePersonMainName());
            appointedMainPersonInfo.setPersonOrgName(saveDto.getHandleOrgName());
            appointedMainPersonInfo.setPersonDeptName(saveDto.getHandleDeptName());
            appointedPersonInfos.add(appointedMainPersonInfo);
            AppointedPersonInfo appointedAssistPersonInfo = new AppointedPersonInfo();
            appointedAssistPersonInfo.setPersonName(saveDto.getHandlePersonAssistName());
            appointedAssistPersonInfo.setPersonOrgName(saveDto.getHandleOrgName());
            appointedAssistPersonInfo.setPersonDeptName(saveDto.getHandleDeptName());
            appointedPersonInfos.add(appointedAssistPersonInfo);
            dto.setAppointedPersonInfoList(appointedPersonInfos);
            caseSourceFlowRecordService.saveCommonFlowRecord(dto);
            //保存案源办案人员信息
            CaseSourceHandlePersonRecordSaveDto caseSourceHandlePersonRecordSaveDto = new CaseSourceHandlePersonRecordSaveDto();
            BeanUtils.copyProperties(saveDto, caseSourceHandlePersonRecordSaveDto);
            caseSourceHandlePersonRecordSaveDto.setCaseSourceId(id);
            caseSourceHandlePersonRecordSaveDto.setHandlePersonId(saveDto.getHandlePersonMainId());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonName(saveDto.getHandlePersonMainName());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonType(Constant.STRING_1);
            caseSourceHandlePersonRecordService.saveCaseSourceHandlePersonRecord(caseSourceHandlePersonRecordSaveDto);
            caseSourceHandlePersonRecordSaveDto.setHandlePersonId(saveDto.getHandlePersonAssistId());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonName(saveDto.getHandlePersonAssistName());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonType(Constant.STRING_2);
            caseSourceHandlePersonRecordService.saveCaseSourceHandlePersonRecord(caseSourceHandlePersonRecordSaveDto);
        }
    }

    /**
     * 附件保存
     *
     * @param id
     * @param saveDto
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveCaseSourceMaterialRecord(String id, UserDTO userDTO, CaseSourceRegisterMainInfoDto saveDto) {
        List<CaseSourceMaterialRecord> caseSourceMaterialRecords = saveDto.getCaseSourceMaterialRecords();
        if (null != caseSourceMaterialRecords && caseSourceMaterialRecords.size() > 0) {
            caseSourceMaterialRecords.forEach(caseSourceMaterialRecord -> {
                if (StringUtils.isBlank(caseSourceMaterialRecord.getId())){
                    caseSourceMaterialRecord.setId(StringUtils.uuid());
                    caseSourceMaterialRecord.setCaseSourceId(id);
                    caseSourceMaterialRecord.setUploadTime(LocalDateTime.now());
                    caseSourceMaterialRecord.setUploadUserId(userDTO.getUserId().toString());
                    caseSourceMaterialRecord.setUploadUserName(userDTO.getRealName());
                    caseSourceMaterialRecord.setIsDelete(Constant.STRING_0);
                    caseSourceMaterialRecordMapper.insert(caseSourceMaterialRecord);
                }else {
                    caseSourceMaterialRecord.setUploadTime(LocalDateTime.now());
                    caseSourceMaterialRecordMapper.updateByPrimaryKeySelective(caseSourceMaterialRecord);
                }
            });
        }
    }

    /**
     * 当事人信息保存
     *
     * @param caseSourcePartyInfos
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    @Override
    public void saveCaseSourcePartyInfo(String id, List<CaseSourcePartyInfo> caseSourcePartyInfos) {
        if (null != caseSourcePartyInfos && caseSourcePartyInfos.size() > 0) {
            caseSourcePartyInfos.forEach(caseSourcePartyInfo -> {
                if (StringUtils.isBlank(caseSourcePartyInfo.getId())){
                    caseSourcePartyInfo.setId(StringUtils.uuid());
                    caseSourcePartyInfo.setCaseSourceId(id);
                    caseSourcePartyInfo.setCreateTime(LocalDateTime.now());
                    caseSourcePartyInfo.setStatus(Constant.STRING_1);
                    caseSourcePartyInfoMapper.insert(caseSourcePartyInfo);
                } else {
                    caseSourcePartyInfo.setUpdateTime(LocalDateTime.now());
                    caseSourcePartyInfoMapper.updateByPrimaryKeySelective(caseSourcePartyInfo);
                }
            });
        }
    }
    /**
     * 案源修改
     * @author liyafeng
     * @date 2022/12/29
      * @param saveDto
     * @return {@link int}
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int editCaseSourceRegisterMainInfo(CaseSourceRegisterMainInfoDto saveDto) {
        String id=saveDto.getId();
        if(StringUtils.isBlank(id)){
            throw new BusinessException("案源id不能为空");
        }
        UserDTO userDTO=UserUtil.getUserInfo();
        //案源信息修改
        int num=saveCaseSourceMainInfo(id, userDTO, saveDto);
        //当事人信息修改
        editCaseSourcePartyInfo(id, saveDto.getCaseSourcePartyInfoList());
        //附件修改
        editCaseSourceMaterialRecord(id, userDTO, saveDto);
        //无效原有案源登记表文书
        //查询案源登记参数配置
        String busiParamId = Constant.QS_BUSI_PARAM_ID;
        String documentKindCode = DocumentKindEnum.DOC_KIND_DK1AJLYDJB.getCode();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, documentKindCode);
        String documentCatalogCode = paramDocumentInfo.getDocumentCatalogCode();
        CaseSourceDocumentRecord caseDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(id, documentCatalogCode, null);
        CaseSourceDocumentRecord updateCaseSourceDocumentRecord=new CaseSourceDocumentRecord();
        updateCaseSourceDocumentRecord.setId(caseDocumentRecord.getId());
        updateCaseSourceDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
        caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseSourceDocumentRecord);

        //重新生成案源登记表文书
        CaseSourceAppointInfo appointInfo = new CaseSourceAppointInfo();
        if (StringUtils.isNotBlank(saveDto.getHandlePersonMainId())) {
            appointInfo.setCluAppointUserId(saveDto.getHandlePersonMainId());
            appointInfo.setCluAppointUserName(saveDto.getHandlePersonMainName());
            appointInfo.setCluAssignDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        }
        appointInfo.setOriginDocumentId(caseDocumentRecord.getId());
        appointInfo.setOriginDocumentNumber(caseDocumentRecord.getDocumentNumber());
        saveCaseSourceRegisterDoc(id, CaseSourceOperateTypeEnum.MODIFY.getCode(), appointInfo);

        return num;
    }

    /**
     * 获取案源信息
     * @param searchDto 查询对象
     * @return  案源信息
     * @author lilihao
     * @date 2023/2/6 19:14
     */
    @Override
    public List<CaseSourceRegisterMainInfo> getCaseSourceRegisterInfo(CaseSearchDto searchDto) {
        PageHelper.startPage(1, 10);
        Example example = new Example(CaseSourceRegisterMainInfo.class);
        if (StrUtil.isNotBlank(searchDto.getId())){
            example.createCriteria().andEqualTo("id",searchDto.getId());
        }

        if (StrUtil.isNotBlank(searchDto.getCaseName())){
            example.createCriteria().andLike("caseSourceName",searchDto.getCaseName()+"%");
        }

        if (StrUtil.isNotBlank(searchDto.getCaseDesc())){
            example.createCriteria().andLike("caseSourceDesc",searchDto.getCaseDesc()+"%");
        }

        if (StrUtil.isNotBlank(searchDto.getCaseActsCode())){
            example.createCriteria().andEqualTo("caseSourceAppActsCode",searchDto.getCaseActsCode());
        }
        return caseSourceRegisterMainInfoMapper.selectByExample(example);
    }

    /**
     * 删除案源信息
     * @param id 案源唯一标识
     * @return
     * @author lilihao
     * @date 2023/2/8 1:07
     */
    @Override
    public int delCaseSourceRegisterInfo(String id) {
        return caseSourceRegisterMainInfoMapper.deleteByPrimaryKey(id);
    }

    /**
     * 附件修改
     * @author liyafeng
     * @date 2022/12/30
      * @param id
     * @param userDTO
     * @param saveDto
     * @return
     */
    private void editCaseSourceMaterialRecord(String id, UserDTO userDTO, CaseSourceRegisterMainInfoDto saveDto) {
        //无效原有附件
        caseSourceMaterialRecordMapper.updateCaseSourceMaterialRecordInvalidBySourceId(id);
        //新增附件
        List<CaseSourceMaterialRecord> caseSourceMaterialRecords = saveDto.getCaseSourceMaterialRecords();
        if (null != caseSourceMaterialRecords && caseSourceMaterialRecords.size() > 0) {
            caseSourceMaterialRecords.forEach(caseSourceMaterialRecord -> {
                    caseSourceMaterialRecord.setId(StringUtils.uuid());
                    caseSourceMaterialRecord.setCaseSourceId(id);
                    caseSourceMaterialRecord.setUploadTime(LocalDateTime.now());
                    caseSourceMaterialRecord.setUploadUserId(userDTO.getUserId().toString());
                    caseSourceMaterialRecord.setUploadUserName(userDTO.getRealName());
                    caseSourceMaterialRecord.setIsDelete(Constant.STRING_0);
                    caseSourceMaterialRecordMapper.insert(caseSourceMaterialRecord);
            });
        }
    }

    /**
     * 当事人信息修改
     * @author liyafeng
     * @date 2022/12/30
      * @param id
     * @param caseSourcePartyInfos
     * @return
     */
    private void editCaseSourcePartyInfo(String id, List<CaseSourcePartyInfo> caseSourcePartyInfos) {
        //无效原有当事人信息
        caseSourcePartyInfoMapper.updateCaseSourcePartyInfoInvalidBySourceId(id);
        //新增修改当事人信息
        if (null != caseSourcePartyInfos && caseSourcePartyInfos.size() > 0) {
            caseSourcePartyInfos.forEach(caseSourcePartyInfo -> {
                caseSourcePartyInfo.setId(StringUtils.uuid());
                caseSourcePartyInfo.setCaseSourceId(id);
                caseSourcePartyInfo.setCreateTime(LocalDateTime.now());
                caseSourcePartyInfo.setStatus(Constant.STRING_1);
                caseSourcePartyInfoMapper.insert(caseSourcePartyInfo);
            });
        }
    }

    /**
     * 案源主表保存
     *
     * @param id
     * @param userDTO
     * @param saveDto
     * @return {@link int}
     * @author liyafeng
     * @date 2022/8/18
     */
    private int saveCaseSourceMainInfo(String id, UserDTO userDTO, CaseSourceRegisterMainInfoDto saveDto) {
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = new CaseSourceRegisterMainInfo();
        BeanUtils.copyProperties(saveDto, caseSourceRegisterMainInfo);
        caseSourceRegisterMainInfo.setId(id);
        //根据案源来源组装caseSourceDesc
        String caseSourceDesc = getCaseSourceDesc(saveDto);
        caseSourceRegisterMainInfo.setCaseSourceDesc(caseSourceDesc);
        caseSourceRegisterMainInfo.setBusiParamId(getBusiParamId(saveDto.getLineCode(),userDTO.getAreaCode()));
        String partyName = "";
        List<CaseSourcePartyInfo> caseSourcePartyInfoList = saveDto.getCaseSourcePartyInfoList();
        if (ObjectUtil.isNotEmpty(caseSourcePartyInfoList) && caseSourcePartyInfoList.size() > 0) {
            if (caseSourcePartyInfoList.size() == 1) {
                partyName = caseSourcePartyInfoList.get(0).getPartyName();
            } else {
                List<CaseSourcePartyInfo> legalList = caseSourcePartyInfoList.stream().filter(e -> PartyTypeEnum.LEGAL.getCode().equals(e.getPartyType())).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(legalList) && legalList.size() > 0) {
                    partyName = legalList.get(0).getPartyName() + "等" + caseSourcePartyInfoList.size() + "个当事人";
                } else {
                    List<CaseSourcePartyInfo> personList = caseSourcePartyInfoList.stream().filter(e -> PartyTypeEnum.PERSON.getCode().equals(e.getPartyType())).collect(Collectors.toList());
                    partyName = personList.get(0).getPartyName() + "等" + caseSourcePartyInfoList.size() + "个当事人";
                }
            }
        }
        caseSourceRegisterMainInfo.setPartyName(partyName);
        //todo 暂时写死
        caseSourceRegisterMainInfo.setCaseSourceAppId("CFBAXT");
        LocalDateTime nowDate = LocalDateTime.now();
        if(StringUtils.isBlank(saveDto.getId())) {
            caseSourceRegisterMainInfo.setCreateTime(Date.from(nowDate.atZone(ZoneId.systemDefault()).toInstant()));
        }
        // 判断是不是人设，是人设添加处置期限
        if (Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0,4))) {
            //修改成5个工作日
            LocalDateTime now = LocalDateTime.now();
            String startDate = now.toLocalDate().toString();
            ConfigEndDayQueryDto q = new ConfigEndDayQueryDto();
            q.setStartDate(startDate);
            q.setBeforeOrAfterSign(Constant.STRING_AFTER);
            q.setType(Constant.STRING_0);
            q.setDayCount(5);
            q.setIsContainStartDay(YesOrNoEnum.NO.getCode());
            LocalDate periodEndDate = configWorkRestDayInfoService.getPeriodEndDate(q);
            caseSourceRegisterMainInfo.setTermTime(Date.from(periodEndDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
            //caseSourceRegisterMainInfo.setTermTime(Date.from(nowDate.plusDays(5).atZone(ZoneId.systemDefault()).toInstant()));
        }
        if (StringUtils.isBlank(saveDto.getId())){
            caseSourceRegisterMainInfo.setCreateUserId(userDTO.getUserId().toString());
            caseSourceRegisterMainInfo.setCreateUserName(userDTO.getRealName());
            caseSourceRegisterMainInfo.setCreateUserDeptCode(userDTO.getDeptCode());
            caseSourceRegisterMainInfo.setCreateUserDeptName(userDTO.getDeptName());
            caseSourceRegisterMainInfo.setCreateUserOrgCode(userDTO.getOrgCode());
            caseSourceRegisterMainInfo.setCreateUserOrgName(userDTO.getOrgName());
            if (StringUtils.isBlank(saveDto.getHandlePersonMainId())) {
                caseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
                caseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYDJ);
            } else {
                caseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.PRE_SURVEY.getIndex());
                caseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYZP);
                caseSourceRegisterMainInfo.setDealTime(new Date());
                caseSourceRegisterMainInfo.setHandleOrgCode(userDTO.getOrgCode());
                caseSourceRegisterMainInfo.setHandleOrgName(userDTO.getOrgName());
                caseSourceRegisterMainInfo.setHandleDeptCode(userDTO.getDeptCode());
                caseSourceRegisterMainInfo.setHandleDeptName(userDTO.getDeptName());
                saveDto.setHandleOrgCode(userDTO.getOrgCode());
                saveDto.setHandleOrgName(userDTO.getOrgName());
                //新增案源事件-证据端
                //saveCaseSourceEvent(saveDto,id);
            }
            return caseSourceRegisterMainInfoMapper.insert(caseSourceRegisterMainInfo);
        }else {
            return caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(caseSourceRegisterMainInfo);
        }
    }

    /**
     * 描述：生成案源登记文书
     *
     * @author shishengyao
     * @date 2022/08/19
     */
    @Override
    public void saveCaseSourceRegisterDoc(String caseSourceId, String caseSourceOperateType, CaseSourceAppointInfo sourceAppointInfo) {
        CSourceDocCommonOperateSaveDto commonOperateSaveDto = new CSourceDocCommonOperateSaveDto();
        //查询主表信息
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);

        //查询案源登记参数配置
        String busiParamId = Constant.QS_BUSI_PARAM_ID;
        String documentKindCode = DocumentKindEnum.DOC_KIND_DK1AJLYDJB.getCode();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, documentKindCode);
        String documentCatalogCode = paramDocumentInfo.getDocumentCatalogCode();

        CaseSourceDocumentRecord caseDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(caseSourceId, documentCatalogCode, null);
        HashMap<String, Object> docDataMap = new HashMap<>();
        CaseSourceRegisterDocAssembleDataDto assembleDataDto = new CaseSourceRegisterDocAssembleDataDto();

        commonOperateSaveDto.setDocumentCatalogCode(documentCatalogCode);

        BeanUtils.copyProperties(caseSourceRegisterMainInfo, assembleDataDto);
        assembleDataDto.setCaseSourceName(CaseSourceEnum.getValueByCode(caseSourceRegisterMainInfo.getCaseSource())+" "+CaseSourceEnum.getValueByCode(caseSourceRegisterMainInfo.getCaseSourceReplenishId()));
        assembleDataDto.setRegisterTimeStr(DateUtils.formatDate(caseSourceRegisterMainInfo.getRegisterTime(), "yyyy年M月d日"));
        //assembleDataDto.setCreateDate(DateUtils.formatDate(caseSourceRegisterMainInfo.getCreateTime(), "yyyy年M月d日"));
        assembleDataDto.setCreateDate(DateUtils.formatDate(caseSourceRegisterMainInfo.getRegisterTime(), "yyyy年M月d日"));
        String caseSourceDesc = caseSourceRegisterMainInfo.getCaseSourceDesc();
        String case_source = caseSourceRegisterMainInfo.getCaseSource();
        if (CaseSourceEnum.CASE_SOURCE_SHJB.getCode().equals(case_source)) {
            List<CaseSourceComplaintReportPersonInfo> complaintReportPersonList = new ArrayList<>();
            //社会举报
            if (YesOrNoEnum.NO.getCode().equals(caseSourceRegisterMainInfo.getIsAnonymous())) {
                List<ReportPersonInfo> jsonList = JSONArray.parseArray(caseSourceDesc, ReportPersonInfo.class);
                for (ReportPersonInfo reportPersonInfo : jsonList) {
                    CaseSourceComplaintReportPersonInfo complaintReportPersonInfo = new CaseSourceComplaintReportPersonInfo();
                    if (PartyTypeEnum.PERSON.getCode().equals(reportPersonInfo.getReportPersonType())) {
                        complaintReportPersonInfo.setComplaintPersonName(BaseUtil.transferNullToSlash(reportPersonInfo.getReportPersonName()));
                        String idCardTypeName = CertTypeEnum.getValueByCode(reportPersonInfo.getIdcardType());
                        String complaintPersonCert = "/";
                        if (!ObjectUtils.isEmpty(reportPersonInfo.getIdcardCode())) {
                            complaintPersonCert = reportPersonInfo.getIdcardCode();
                            if (!ObjectUtils.isEmpty(idCardTypeName)) {
                                complaintPersonCert = idCardTypeName + complaintPersonCert;
                            }
                        }
                        complaintReportPersonInfo.setComplaintPersonCert(complaintPersonCert);
                        complaintReportPersonInfo.setComplaintPersonPhone(BaseUtil.transferNullToSlash(reportPersonInfo.getContactPhone()));
                        complaintReportPersonInfo.setComplaintPersonPostcode(BaseUtil.transferNullToSlash(reportPersonInfo.getAbbreviationCode()));
                        complaintReportPersonInfo.setComplaintPersonAddress(BaseUtil.transferNullToSlash(reportPersonInfo.getContactAddressAreaDetailName()));
                        complaintReportPersonInfo.setComplaintUnitName(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintUnitLegalName(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintUnitPhone(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintUnitPostcode(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintUnitAddress(BaseUtil.transferNullToSlash(null));
                    } else {
                        complaintReportPersonInfo.setComplaintPersonName(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintPersonCert(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintPersonPhone(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintPersonPostcode(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintPersonAddress(BaseUtil.transferNullToSlash(null));
                        complaintReportPersonInfo.setComplaintUnitName(BaseUtil.transferNullToSlash(reportPersonInfo.getReportPersonName()));
                        complaintReportPersonInfo.setComplaintUnitLegalName(BaseUtil.transferNullToSlash(reportPersonInfo.getLegalRepresentName()));
                        complaintReportPersonInfo.setComplaintUnitPhone(BaseUtil.transferNullToSlash(reportPersonInfo.getContactPhone()));
                        complaintReportPersonInfo.setComplaintUnitPostcode(BaseUtil.transferNullToSlash(reportPersonInfo.getAbbreviationCode()));
                        complaintReportPersonInfo.setComplaintUnitAddress(BaseUtil.transferNullToSlash(reportPersonInfo.getContactAddressAreaDetailName()));
                    }
                    complaintReportPersonList.add(complaintReportPersonInfo);
                }

            }
            assembleDataDto.setComplaintReportPersonList(complaintReportPersonList);
        } else if (CaseSourceEnum.CASE_SOURCE_SJXZJGJB.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_XJXZJGBQ.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(case_source)) {
            //部门移送/上级行政机关交办/下级行政机关报请采集信息
            List<CaseSourceTransferDeptInfo> transferDeptList = new ArrayList<>();
            CaseSourceTransferDeptInfo sourceTransferDeptInfo = new CaseSourceTransferDeptInfo();
            CaseSourceOrgInfo caseSourceOrgInfo = JSONObject.parseObject(caseSourceDesc, CaseSourceOrgInfo.class);
            sourceTransferDeptInfo.setTransferDeptName(caseSourceOrgInfo.getOrgName());
            sourceTransferDeptInfo.setTransferDeptLinkPerson(caseSourceOrgInfo.getContactName());
            sourceTransferDeptInfo.setTransferDeptLinkAddress(BaseUtil.transferNullToSlash(caseSourceOrgInfo.getContactAddressAreaDetailName()));
            sourceTransferDeptInfo.setTransferDeptLinkTel(BaseUtil.transferNullToSlash(caseSourceOrgInfo.getContactTel()));
            sourceTransferDeptInfo.setTransferDeptPostcode(BaseUtil.transferNullToSlash(caseSourceOrgInfo.getPostCode()));
            transferDeptList.add(sourceTransferDeptInfo);
            assembleDataDto.setTransferDeptList(transferDeptList);

        } else if (CaseSourceEnum.CASE_SOURCE_FXCZF.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_JGJCBG.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_QT.getCode().equals(case_source)) {
            //非现场执法/机构检测报告/其他案源采集信息
        } else if (CaseSourceEnum.CASE_SOURCE_ZXZJCZFX.getCode().equals(case_source)) {
            //在行政检查中发现
            List<CaseSourceCheckPersonInfo> checkPersonList = new ArrayList<>();
            CaseSourceCheckPersonInfo checkPersonInfo = new CaseSourceCheckPersonInfo();
            CaseSourceRegisterDetailInfo registerDetailInfo = caseSourceRegisterDetailInfoService.getCaseSourceRegisterDetailInfoByCaseSourceId(caseSourceId);
            checkPersonInfo.setCheckMainPersonName(registerDetailInfo.getCheckMainPersonName());
            checkPersonInfo.setCheckMainLawEnforcementCert(BaseUtil.transferNullToSlash(registerDetailInfo.getCheckMainLawEnforcementCert()));
            checkPersonInfo.setCheckAssistPersonName(BaseUtil.transferNullToSlash(registerDetailInfo.getCheckAssistPersonName()));
            checkPersonInfo.setCheckAssistLawEnforcementCert(BaseUtil.transferNullToSlash(registerDetailInfo.getCheckAssistLawEnforcementCert()));
            checkPersonList.add(checkPersonInfo);
            assembleDataDto.setCheckPersonList(checkPersonList);
        }
        //预调查
        if (ObjectUtil.isNotEmpty(sourceAppointInfo) ) {
            if(ObjectUtil.isNotEmpty(sourceAppointInfo.getCluAppointUserId())){
                //  签名校验
                String handlePersonSignPic = commonService.getHandleSignData(sourceAppointInfo.getCluAppointUserId());
                if ("true".equals(isCheckHandleSign)) {
                    if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                        throw new BusinessException("办案人员" + sourceAppointInfo.getCluAppointUserName() + "的签名为空!");
                    }
                }
                assembleDataDto.setTransferDeptAssistPersonPic(handlePersonSignPic);
                assembleDataDto.setTransferDeptOpinion(sourceAppointInfo.getCluAppointDesc());
                assembleDataDto.setTransferDeptOpinionDate(sourceAppointInfo.getCluAssignDate());
            }
            commonOperateSaveDto.setOriginDocumentNumber(sourceAppointInfo.getOriginDocumentNumber());
            commonOperateSaveDto.setOriginDocumentId(sourceAppointInfo.getOriginDocumentId());
        }
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)
                && ObjectUtil.isNotEmpty(caseDocumentRecord.getDocumentContent())) {
            JSONObject jsonObject = JSONObject.parseObject(caseDocumentRecord.getDocumentContent());
            assembleDataDto.setOrgStandardName(jsonObject.getString("orgStandardName"));
        }
        // 获取标准文书抬头
        if (ObjectUtil.isEmpty(assembleDataDto.getOrgStandardName())) {
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseSourceRegisterMainInfo.getCreateUserOrgCode(),caseSourceRegisterMainInfo.getCreateUserDeptCode());
            assembleDataDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
        }

        docDataMap = BaseUtil.javaToMap(assembleDataDto);
        commonOperateSaveDto.setCaseSourceOperateType(caseSourceOperateType);
        commonOperateSaveDto.setDataMap(docDataMap);
        commonOperateSaveDto.setCaseSourceId(caseSourceId);
        Map<String, Object> map = icSourceDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
    }

    /**
     * 获取案源详情
     *
     * @param caseSourceDetailDto
     * @return {@link CaseSourceDetailVo}
     * @author liyafeng
     * @date 2022/8/15
     */
    @Override
    public CaseSourceDetailVo getCaseSourceDetail(CaseSourceDetailDto caseSourceDetailDto) {
        CaseSourceDetailVo vo = new CaseSourceDetailVo();
        String caseSourceId=caseSourceDetailDto.getCaseSourceId();
        //获取案源主表数据
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceDetailDto.getCaseSourceId());
        BeanUtils.copyProperties(caseSourceRegisterMainInfo, vo);
        if (CaseSourceEnum.CASE_SOURCE_SHJB.getCode().equals(vo.getCaseSource())) {
            List<ReportPersonInfo> jsonList = JSONArray.parseArray(vo.getCaseSourceDesc(), ReportPersonInfo.class);
            jsonList.forEach(reportPersonInfo -> {
                if (Constant.STRING_1.equals(reportPersonInfo.getReportPersonType())) {
                    reportPersonInfo.setIdcardType(CertTypeEnum.getValueByCode(reportPersonInfo.getIdcardType()));
                }
            });
            vo.setReportPersonInfos(jsonList);
        } else if (CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(vo.getCaseSource()) || CaseSourceEnum.CASE_SOURCE_SJXZJGJB.getCode().equals(vo.getCaseSource()) || CaseSourceEnum.CASE_SOURCE_XJXZJGBQ.getCode().equals(vo.getCaseSource())) {
            CaseSourceOrgInfo caseSourceOrgInfo = JSONObject.parseObject(vo.getCaseSourceDesc(), CaseSourceOrgInfo.class);
            //统一社会信用代码处理
            if (ObjectUtil.isNotEmpty(caseSourceOrgInfo) && ObjectUtil.isEmpty(caseSourceOrgInfo.getOrgUniscid())) {
                //无部门编码, 设置部门名称为空, 让用户在页面自己选择
                caseSourceOrgInfo.setOrgName(null);
            }
            vo.setCaseSourceOrgInfo(caseSourceOrgInfo);
        } else {
            vo.setOtherCaseSourceDesc(vo.getCaseSourceDesc());
        }
        CaseSourceRegisterDetailInfo caseSourceRegisterDetailInfo = caseSourceRegisterDetailInfoMapper.selectByPrimaryKey(caseSourceDetailDto.getCaseSourceId());
        vo.setCaseSourceRegisterDetailInfo(caseSourceRegisterDetailInfo);
        //查询最新的流转状态
        //CaseSourceFlowRecord caseSourceFlowRecord = caseSourceFlowRecordService.getLastCaseSourceFlowRecord(caseSourceDetailDto.getCaseSourceId());
        String isShowButton = "";
        UserDTO userDTO = UserUtil.getUserInfo();
        String userId = userDTO.getUserId().toString();
        String orgCode = userDTO.getOrgCode();
        //修改为按案件主表的流程阶段编码来判断 2022-10-17
        //if (Constant.CASE_SOURCE_STAGE_AYZP.equals(caseSourceFlowRecord.getFlowStageType()) && (userId.equals(caseSourceRegisterMainInfo.getHandlePersonMainId()) || userId.equals(caseSourceRegisterMainInfo.getHandlePersonAssistId())) && orgCode.equals(caseSourceRegisterMainInfo.getHandleOrgCode())) {
        if (Constant.CASE_SOURCE_STAGE_AYZP.equals(caseSourceRegisterMainInfo.getCaseSourceStageCode()) && (userId.equals(caseSourceRegisterMainInfo.getHandlePersonMainId()) || userId.equals(caseSourceRegisterMainInfo.getHandlePersonAssistId())) && orgCode.equals(caseSourceRegisterMainInfo.getHandleOrgCode())) {
            isShowButton = Constant.STRING_1;
        } else {
            isShowButton = Constant.STRING_0;
        }
        vo.setIsShowButton(isShowButton);
        Example partyExample = new Example(CaseSourcePartyInfo.class);
        partyExample.createCriteria().andEqualTo("caseSourceId", caseSourceDetailDto.getCaseSourceId()).andEqualTo("status", Constant.STRING_1);
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(partyExample);
        vo.setCaseSourcePartiesType(Constant.STRING_0);
        if (null != caseSourcePartyInfos && caseSourcePartyInfos.size() > 1) {
            vo.setCaseSourcePartiesType(Constant.STRING_1);
        }
        //附件查询
        Example materialExample = new Example(CaseSourceMaterialRecord.class);
        materialExample.createCriteria().andEqualTo("caseSourceId", caseSourceDetailDto.getCaseSourceId()).andEqualTo("isDelete", Constant.STRING_0);
        List<CaseSourceMaterialRecord> caseSourceMaterialRecordList = caseSourceMaterialRecordMapper.selectByExample(materialExample);
        vo.setCaseSourceMaterialRecordList(caseSourceMaterialRecordList);
        List<CaseStageLinkRelateDocumentVo> materialList = new ArrayList<>();
        caseSourceMaterialRecordList.forEach(caseSourceMaterialRecord -> {
            CaseStageLinkRelateDocumentVo caseStageLinkRelateDocumentVo = new CaseStageLinkRelateDocumentVo();
            caseStageLinkRelateDocumentVo.setDocumentUrl(caseSourceMaterialRecord.getMaterialUrl());
            caseStageLinkRelateDocumentVo.setDocumentId(caseSourceMaterialRecord.getId());
            caseStageLinkRelateDocumentVo.setDocumentCreateTime(caseSourceMaterialRecord.getUploadTime());
            caseStageLinkRelateDocumentVo.setCreateUserName(caseSourceMaterialRecord.getUploadUserName());
            caseStageLinkRelateDocumentVo.setDocumentCatalogName(caseSourceMaterialRecord.getMaterialName());
            caseStageLinkRelateDocumentVo.setDocumentKindName(caseSourceMaterialRecord.getMaterialName());
            if (!ObjectUtils.isEmpty(caseSourceMaterialRecord.getEvidenceUid())) {
                //证据文件
                caseStageLinkRelateDocumentVo.setIsEvidenceDoc(YesOrNoEnum.YES.getCode());
            }
            materialList.add(caseStageLinkRelateDocumentVo);
        });
        //当前阶段可选审批表列表
        List<CaseDetailOperateDocInfoVo> caseDetailOperateApprovalTableInfoVoList = new ArrayList<>();
        //当前阶段可选文书列表
        List<CaseDetailOperateDocInfoVo> caseDetailOperateDocInfoVoList = new ArrayList<>();
        //查询所有案源文书
        Example example = new Example(ConfigBusiParamDocumentInfo.class);

        // 特殊处理自然资源条线参数配置
        String  busiParamId=caseSourceRegisterMainInfo.getBusiParamId();
        if (ObjectUtil.isNotEmpty(busiParamId)){
            example.createCriteria().andLike("applyGroup", "%AY%").andEqualTo("busiParamId",busiParamId);
        }else {
            example.createCriteria().andLike("applyGroup", "%AY%");
        }
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(example);
        configBusiParamDocumentInfos.forEach(configBusiParamDocumentInfo -> {
            CaseDetailOperateDocInfoVo caseDetailOperateDocInfoVo = new CaseDetailOperateDocInfoVo();
            caseDetailOperateDocInfoVo.setDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode());
            caseDetailOperateDocInfoVo.setDocumentKindName(configBusiParamDocumentInfo.getDocumentKindName());
            caseDetailOperateDocInfoVo.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
            caseDetailOperateDocInfoVo.setIsNeedApproval(configBusiParamDocumentInfo.getIsApprove());
            caseDetailOperateDocInfoVo.setAllRelationDocCatalogCodeList(null);
            caseDetailOperateDocInfoVo.setCaseDocumentTypeFlag(null);
            caseDetailOperateDocInfoVo.setCaseId(caseSourceDetailDto.getCaseSourceId());
            List<CasePartyRelateDocInfoVo> casePartiesKeyInfoVos = new ArrayList<>();
            CasePartyRelateDocInfoVo casePartyRelateDocInfo;
            for (CaseSourcePartyInfo party : caseSourcePartyInfos) {
                casePartyRelateDocInfo = new CasePartyRelateDocInfoVo();
                BeanUtils.copyProperties(party, casePartyRelateDocInfo);
                casePartyRelateDocInfo.setPartyId(party.getId());
                casePartyRelateDocInfo.setIsAddedThisDoc(YesOrNoEnum.NO.getCode());
                //查看该当事人是否已经添加该文书
                Example queryCountExample = new Example(CaseSourceDocumentRecord.class);
                queryCountExample.createCriteria().andEqualTo("caseSourceId", caseSourceDetailDto.getCaseSourceId())
                        .andEqualTo("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode())
                        .andEqualTo("partyId", casePartyRelateDocInfo.getPartyId())
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                int count = caseSourceDocumentRecordMapper.selectCountByExample(queryCountExample);
                if (count > 0) {
                    casePartyRelateDocInfo.setIsAddedThisDoc(YesOrNoEnum.YES.getCode());
                }
                casePartyRelateDocInfo.setIsAddedThisDocName(YesOrNoEnum
                        .getValueByCode(casePartyRelateDocInfo.getIsAddedThisDoc()));
                casePartiesKeyInfoVos.add(casePartyRelateDocInfo);
            }
            caseDetailOperateDocInfoVo.setDocRelatePartiesList(casePartiesKeyInfoVos);
            caseDetailOperateDocInfoVo.setDocumentLinkObjectType(configBusiParamDocumentInfo.getDocumentLinkObjectType());
            //审批表
            if (Constant.STRING_1.equals(configBusiParamDocumentInfo.getDocumentType())) {
                caseDetailOperateApprovalTableInfoVoList.add(caseDetailOperateDocInfoVo);
                //caseDetailOperateDocInfoVo.setDocIsExistsAndWaitToSignRelatedPartyIdList();
            }
            //法律文书
            if (Constant.STRING_2.equals(configBusiParamDocumentInfo.getDocumentType())) {
                caseDetailOperateDocInfoVoList.add(caseDetailOperateDocInfoVo);
            }
        });
        vo.setCaseDetailOperateApprovalTableInfoVoList(caseDetailOperateApprovalTableInfoVoList);
        vo.setCaseDetailOperateDocInfoVoList(caseDetailOperateDocInfoVoList);
        //文书列表
        CaseSourceLinkRelateDocumentQueryDto query = new CaseSourceLinkRelateDocumentQueryDto();
        query.setCaseSourceId(caseSourceDetailDto.getCaseSourceId());
        query.setDocumentRecordStatus(Constant.STRING_1);
        List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentList = caseSourceDocumentRecordService.getCaseStageLinkRelateDocumentInfo(query);
        for (CaseStageLinkRelateDocumentVo caseStageLinkRelateDocumentVo : caseStageLinkRelateDocumentList) {
            //多当事人并且文书针对人
            if (Constant.STRING_2.equals(caseStageLinkRelateDocumentVo.getDocumentLinkObjectType()) && caseSourcePartyInfos.size() > 1) {
                String partyId = caseStageLinkRelateDocumentVo.getPartyId();
                String[] partyIdArr = partyId.split(",");
                if (partyIdArr.length == 1) {
                    CaseSourcePartyInfo caseSourcePartyInfo = caseSourcePartyInfoMapper.selectByPrimaryKey(partyId);
                    if (null != caseSourcePartyInfo) {
                        String documentCatalogName = caseStageLinkRelateDocumentVo.getDocumentCatalogName() + "(" + caseSourcePartyInfo.getPartyName() + ")";
                        caseStageLinkRelateDocumentVo.setDocumentCatalogName(documentCatalogName);
                    }
                }
            }
        }
        //加入线下上传文书
        List<CaseStageLinkRelateDocumentVo> offlineDocList = caseOfflineDocumentRecordService.getOfflineDocInfoToCaseStageLinkRelateDocument(caseSourceDetailDto.getCaseSourceId());
        caseStageLinkRelateDocumentList.addAll(materialList);
        caseStageLinkRelateDocumentList.addAll(offlineDocList);
        //查询不予立案审批表
        CaseStageLinkRelateDocumentQueryDto dto = new CaseStageLinkRelateDocumentQueryDto();
        dto.setCaseId(caseSourceDetailDto.getCaseSourceId());
        //todo  不予立案审批表
        //busiParamId存储了，就不写死
        if (ObjectUtil.isNotEmpty(busiParamId)){
         ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_DK1BYLASPB.getCode());
         dto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        }else {
            dto.setDocumentCatalogCode("DC1A0223300BYLASPB000000001");
        }
        //查询正常和草稿文书
        dto.setDocumentRecordStatus(Constant.STRING_1_2);
        List<CaseStageLinkRelateDocumentVo> caseStageLinkBylaspbDocumentList
                = caseDocumentRecordService.getCaseStageLinkRelateDocumentInfo(dto);
        if (ObjectUtil.isNotEmpty(busiParamId)){
            // 立案和案源的条线不一样时，查询案件阶段文书用案件的业务参数id
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseSourceId);
            String caseBusiParamId=busiParamId;
            if (!ObjectUtils.isEmpty(caseMainInfo) && ObjectUtil.isNotEmpty(caseMainInfo.getBusiParamId())){
                caseBusiParamId=caseMainInfo.getBusiParamId();
            }
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseBusiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
            dto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        }else {
            dto.setDocumentCatalogCode("DC1A0223300LASPB00000000001");
        }
        List<CaseStageLinkRelateDocumentVo> caseStageLinkLaspbDocumentList
                = caseDocumentRecordService.getCaseStageLinkRelateDocumentInfo(dto);
        caseStageLinkRelateDocumentList.addAll(caseStageLinkBylaspbDocumentList);
        caseStageLinkRelateDocumentList.addAll(caseStageLinkLaspbDocumentList);
        CaseStageDocumentInfoVo caseStageDocumentInfoVo = new CaseStageDocumentInfoVo();
        caseStageDocumentInfoVo.setCaseStageName(CaseSourceStatusEnum.PRE_SURVEY.getName());
        caseStageLinkRelateDocumentList.forEach(item -> {
            item.setDocumentApprovalStatusName(DocumentStatusEnum.getValueByCode(item.getDocumentApprovalStatus()));
        });
        Collections.sort(caseStageLinkRelateDocumentList, (o1, o2) -> o1.getDocumentCreateTime().compareTo(o2.getDocumentCreateTime()));

        //案源移交
        Example transferExample = new Example(CaseTransferRecord.class);
        transferExample.createCriteria().andEqualTo("caseSourceId",caseSourceDetailDto.getCaseSourceId())
                .andEqualTo("transferType", Constant.STRING_3).andEqualTo("deleted", Constant.STRING_0);
        List<CaseTransferRecord> caseTransferRecordList= caseTransferRecordMapper.selectByExample(transferExample);
        caseTransferRecordList.forEach(a -> {
            CaseStageLinkRelateDocumentVo caseStageLinkRelateDocumentVo = new CaseStageLinkRelateDocumentVo();
            //案源id
            caseStageLinkRelateDocumentVo.setSendUid(a.getSendUid());
            //标题
            caseStageLinkRelateDocumentVo.setDocumentCatalogName(String.format("案源移交（%s）", a.getUnitName()));
            //创建人
            caseStageLinkRelateDocumentVo.setCreateUserName(a.getCreator());
            //创建时间
            caseStageLinkRelateDocumentVo.setDocumentCreateTime(a.getCreated().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            //状态
            caseStageLinkRelateDocumentVo.setDocumentApprovalStatusName(a.getStatus());
            //阶段编码
            caseStageLinkRelateDocumentVo.setCaseStageCode(a.getStageCode());
            //移交类型
            caseStageLinkRelateDocumentVo.setTransferType(a.getTransferType());

            caseStageLinkRelateDocumentList.add(caseStageLinkRelateDocumentVo);
        });

        caseStageDocumentInfoVo.setCaseStageRelateDocumentList(caseStageLinkRelateDocumentList);
        vo.setCaseStageDocumentInfoVo(caseStageDocumentInfoVo);
        Date termTime = vo.getTermTime();
        if (!ObjectUtils.isEmpty(termTime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            vo.setTermTimeFormat(sdf.format(termTime));
        }
        vo.setIsEdit(StringUtils.equalsAny(vo.getCaseSourceStageCode(),Constant.CASE_SOURCE_STAGE_AYDJ,Constant.CASE_SOURCE_STAGE_AYFP,Constant.CASE_SOURCE_STAGE_AYZP)
                ? true : false);
        return vo;
    }

    @Override
    public CaseSourceBasicInfoVo getCaseSourceBasicInfoVo(String caseSourceId) {
        CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);
        CaseSourceBasicInfoVo caseSourceBasicInfoVo = new CaseSourceBasicInfoVo();
        BeanUtils.copyProperties(mainInfo, caseSourceBasicInfoVo);
        caseSourceBasicInfoVo.setCaseSourceStatus(mainInfo.getCaseSource());
        caseSourceBasicInfoVo.setCaseSourceStatusName(CaseSourceStatusEnum.getValue(mainInfo.getCaseSource()));
        caseSourceBasicInfoVo.setCaseSourceName(mainInfo.getCaseSourceName());
        caseSourceBasicInfoVo.setCaseSourceDesc(CaseSourceEnum.getValueByCode(mainInfo.getCaseSource()));
        caseSourceBasicInfoVo.setCaseSourceReplenishId(CaseSourceEnum.getValueByCode(mainInfo.getCaseSourceReplenishId()));
        caseSourceBasicInfoVo.setCaseSourceReplenishDesc(CaseSourceEnum.getValueByCode(mainInfo.getCaseSourceReplenishId()));
        //查询案源登记参数配置
        String busiParamId = Constant.QS_BUSI_PARAM_ID;
        String documentKindCode = DocumentKindEnum.DOC_KIND_DK1AJLYDJB.getCode();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, documentKindCode);
        String documentCatalogCode = paramDocumentInfo.getDocumentCatalogCode();
        CaseSourceDocumentRecord caseDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(caseSourceId, documentCatalogCode, null);
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)) {
            caseSourceBasicInfoVo.setCaseSourceNumber(caseDocumentRecord.getDocumentNumber());
        }
        String orgCode = mainInfo.getHandleOrgCode();
        String deptCode=mainInfo.getHandleDeptCode();
        if (ObjectUtil.isEmpty(orgCode)) {
            orgCode = mainInfo.getCreateUserOrgCode();
            deptCode=mainInfo.getCreateUserDeptCode();
        }
        SysDepartParam sysDepartParamByOrgCode = sysDepartParamService.getSysDepartParamByOrgCode(orgCode,deptCode);
        caseSourceBasicInfoVo.setOrgStandardName(sysDepartParamByOrgCode.getOrgStandardName());
        return caseSourceBasicInfoVo;
    }

    /**
     * 获取案源来源描述
     *
     * @param saveDto
     * @return {@link String}
     * @author liyafeng
     * @date 2022/8/14
     */
    private String getCaseSourceDesc(CaseSourceRegisterMainInfoDto saveDto) {
        String caseSourceDesc = "";
        if (CaseSourceEnum.CASE_SOURCE_SHJB.getCode().equals(saveDto.getCaseSource())) {
            caseSourceDesc = JSON.toJSONString(saveDto.getReportPersonInfos());
        } else if (CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(saveDto.getCaseSource()) || CaseSourceEnum.CASE_SOURCE_SJXZJGJB.getCode().equals(saveDto.getCaseSource()) || CaseSourceEnum.CASE_SOURCE_XJXZJGBQ.getCode().equals(saveDto.getCaseSource())) {
            caseSourceDesc = JSON.toJSONString(saveDto.getCaseSourceOrgInfo());
        } else {
            caseSourceDesc = saveDto.getOtherCaseSourceDesc();
        }
        return caseSourceDesc;
    }


    /**
     * 描述： 根据id获取证据预览地址
     *
     * @return {@link Result< String>}
     * @author: zhengqiang
     * @date: 2022/9/5
     * @param: documentId
     **/
    @Override
    public Result<String> getEvidenceLinkByDocumentId(String documentId) {
        CaseSourceMaterialRecord materialRecord = caseSourceMaterialRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(materialRecord)) {
            throw new BusinessException("证据信息不存在");
        }
        String evidenceLink = evidenceInventoryService.getEvidenceLink(materialRecord.getEvidenceUid(), materialRecord.getEvidenceLinkType());
        return Result.success(Constant.STRING_SUCCESS_EN, evidenceLink);
    }

    /**
     * 描述: 案源时效统计
     *
     * @param request
     * @return com.icinfo.cloud.provider.punish.ucase.casemain.vo.ColorSumVo
     * @author zhanghongqiang
     * @Date 2022/10/26
     */
    @Override
    public ColorSumVo getCaseSourceColourStatistic(CaseSourceRegisterMainInfoRequest request) {
        UserDTO userInfo = UserUtil.getUserInfo();
        request.setCreateUserOrgCode(userInfo.getOrgCode());
        request.setCreateUserDeptCode(userInfo.getDeptCode());
        // 派驻机构取部门code进行查询
        if (Constant.STRING_2.equals(userInfo.getDeptType())) {
            request.setFlag(true);
        }
        request.setHandlePersonId(userInfo.getUserId().toString());
        request.setPrescription(null);
        Integer total = caseSourceRegisterMainInfoMapper.selectCaseSourceColourStatistic(request);
        request.setPrescription("red");
        Integer countRed = caseSourceRegisterMainInfoMapper.selectCaseSourceColourStatistic(request);
        request.setPrescription("yellow");
        Integer countYellow = caseSourceRegisterMainInfoMapper.selectCaseSourceColourStatistic(request);
        request.setPrescription("blue");
        Integer countBlue = caseSourceRegisterMainInfoMapper.selectCaseSourceColourStatistic(request);
        ColorSumVo sumVo = new ColorSumVo();
        sumVo.setBlueNum(countBlue);
        sumVo.setRedNum(countRed);
        sumVo.setYellowNum(countYellow);
        sumVo.setTotal(total);
        return sumVo;
    }

    /**
     * 描述：获取业务参数id
     *
     * @param lineCode 行代码
     * @param areaCode 区号
     * @return {@link String }
     * @author shishengyao
     * @date 2022/11/12
     */
    @Override
    public String getBusiParamId(String lineCode, String areaCode){
        //获取办案条线对应的领域
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(lineCode);
        if (ObjectUtil.isNotEmpty(lineDTO)){
            //获取领域下业务参数
            RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
            request.setApplyAreaCode(areaCode);
            request.setApplyFieldCode(lineDTO.getTerritoryCode());
            List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
            if (ObjectUtil.isNotEmpty(configBusiParamMainList) && configBusiParamMainList.size()>0){
                //业务参数Id
                return  configBusiParamMainList.get(0).getId();
            }
        }

        return "";
    }


}
